from datetime import datetime
import random

from django.db import models
from apps.utils.db import table_prefix, BaseModel, CoreModel


def rename_file(instance, filename):
    """重命名图片方法"""
    extension = filename.split('.')[-1]

    day = datetime.now().strftime('%Y/%m/%d')

    fn = datetime.now().strftime('%Y%m%d%H%M%S')
    fn = fn + '_%s%s%s' % (str(random.randint(0, 9)), str(random.randint(0, 9)), str(random.randint(0, 9)))

    new_name = "%s/%s.%s" % (day, fn, extension)

    return new_name


class Files(CoreModel):
    """
    文件表
    """
    name = models.CharField(verbose_name='名称', help_text='名称', max_length=100, null=True, blank=True)
    size = models.IntegerField(verbose_name='文件大小', help_text='文件大小', default=1, null=True, blank=True)
    file = models.FileField(verbose_name='文件路径', upload_to=rename_file)
    # file = models.FileField(upload_to='%Y/%m/%d/', verbose_name='文件路径')

    class Meta:
        db_table = table_prefix + 'files'
        verbose_name = '文件表'
        verbose_name_plural = verbose_name
